
import type { configOptions } from './type'
import { getLocalStorage, getSystemInfo, setLocalStorage } from './util'
import { getPageBasicTiming, resourceLogNeed, collectLogs,  sendBeaconFunc, sendAjaxFunc, caculateSendData  } from './log'

class VeryLog {

  private channel_id: string;

  private env: string;

  private package_name: string;

  private log_url: string;

  protected logList: any[] = []

  constructor(config: configOptions) {

    this.channel_id = config.channel_id

    this.env = config.env

    this.package_name = config.package_name

    this.log_url = config.log_url

  }

  performanceRun() {
    const { Platform: platform, OsVersion: os_version } = getSystemInfo()

    // 支持 PerformanceObserver API
    if (typeof window.PerformanceObserver === 'function') {
      console.log('entryTypes: ', PerformanceObserver.supportedEntryTypes)
      const performanceInstence = new PerformanceObserver((list, obj) => {
        const entries = list.getEntries()
        for (const entry of entries) {
          switch (entry.entryType) {
            case 'resource':
              if (resourceLogNeed(entry)) { // 需要上报的 http 请求
                const { name, duration, startTime, entryType, responseStatus, initiatorType } = entry
                collectLogs({
                  name,
                  duration,
                  startTime,
                  entryType,
                  responseStatus,
                  initiatorType
                })
              }
              break
            case 'navigation':
              console.log('navigation ', entry)
              collectLogs(getPageBasicTiming(entry))
              break
            default:
              if (['paint', 'largest-contentful-paint'].includes(entry.entryType)) {
                const { name, duration, entryType, startTime } = entry
                collectLogs({
                  entryType,
                  name,
                  duration,
                  startTime
                })
              }
          }
        }
        if (window.logData.length > 10) {
          localStorage.removeItem('performance-log')
          this.sendLog()
        }
      })

      performanceInstence.observe({
        entryTypes: ['paint', 'largest-contentful-paint', 'resource', 'navigation']
      })
    } else {
      const unSupportLog = {
        index: 'performance',
        user_id: getLocalStorage('user_id') || '',
        cat_event_name: 'no_performanceObserver',
        cat_event_type: navigator.sendBeacon ? 'sendbeacon' : 'ajax',
        channel_id: this.channel_id,
        current_url: location.href.split('?')[0],
        bhv_time: Date.now(), // 产生日志时间戳
        log_level: 'debug', //
        request_type: 1, // 1,普通的接口请求; 2,请求图片
        os_version: os_version,
        platform: platform,
        env: this.env
      }
      this.logList.push(unSupportLog)
      this.sendLog(true)
    }
  }


  // 收集日志信息
  collectLog(data: object) {
    window.logData.push(caculateSendData(data))
    setLocalStorage('performance-log', window.logData)

    if(this.logList.length >= 10) {
      this.sendLog()
    }
  }

  collectResponse(response: object) {
    if (!window.ajaxLogMap) {
      window.ajaxLogMap = new Map()
    }

    const { config, request } = response
    if (config?.headers?.traceid) {
      window.ajaxLogMap.set(config.headers.traceid, {
        url: config?.url,
        traceid: config.headers.traceid,
        status: request?.status,
        resData: response?.data || {}
      })
    }
  }


  collectAJaxError = (error = {}) => {
    if (!window.ajaxLogMap) {
      window.ajaxLogMap = new Map()
    }
    if (error.response) {
      const { config, status, data } = error.response
      if (config?.headers?.traceid) {
        window.ajaxLogMap.set(config.headers.traceid, {
          url: config?.url,
          traceid: config.headers.traceid,
          status,
          resData: data || {}
        })
      }
    }
  }



  
  // 发送日志信息
  sendLog(immediately = false) {
    const _params = window.logData || []
    const _len = _params.length
    if (_len || mastSend) {
      // const sendParams = _params.splice(0, _len) // 直接取出一段上报
      if (navigator.sendBeacon) { // 支持 sendBeacon
        sendBeaconFunc(window.logData, mastSend)
      } else { // 不支持， 就用常规 ajax方式上报
        sendAjaxFunc(window.logData)
      }
    }
  }
}

export default VeryLog
